/*
 * Semaphore Demo
 * Liu Jinzhu
 * 2018-04-09
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>

void *thread_function(void *arg);

sem_t bin_sem;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];

int main() {

    int res;                			// 保存线程创建返回值
    pthread_t a_thread;    			// 保存线程标识信息
    void *thread_result;   	 		// 线程运行返回值
    res = sem_init(&bin_sem, 0, 0);	// 创建初始化信号量
    if (0 != res) {
    		perror("初始化信号量失败");
    		exit(EXIT_FAILURE);
     }
    res = pthread_create(&a_thread, NULL, thread_function, NULL);
    if (0 != res) {
        perror("线程创建失败");
        exit(EXIT_FAILURE);
     }
    printf("请输入要传送的信息,输入'End'退出\n");
    while(strncmp("end", work_area, 3) != 0) {	// 判断输入是否为end
    	fgets(work_area, WORK_SIZE, stdin);
    	sem_post(&bin_sem);
    }

    printf("等待线程结束...\n");
    res = pthread_join(a_thread, &thread_result);
    if (0 != res) {
        perror("等待线程结束失败");
        exit(EXIT_FAILURE);
    }
    printf("线程已结束\n");
    sem_destroy(&bin_sem);

    exit(EXIT_SUCCESS);

}

void *thread_function(void *arg) {
	sem_wait(&bin_sem);
	while(strncmp("end", work_area, 3) != 0) {	// 判断输入是否为end
		printf("收到%d个字符\n", (int)(strlen(work_area) - 1));
		sem_wait(&bin_sem);
	}

    pthread_exit(NULL);

}
